<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-input v-model="listQuery.shop_id" placeholder="商品ID" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.ishow" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(item,idx) in statusOptions" :key="idx" :label="item.a" :value="item.b" />
      </el-select>

      <el-select v-model="listQuery.isfree" placeholder="分类" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(item,idx) in catypeData" :key="idx" :label="item.a" :value="item.b" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名字" width="180px">
        <template slot-scope="{row}">
          <!-- <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag> -->
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" min-width="110px">
        <template slot-scope="{row}">
          <img style="width:50px;" :src="baseimgurl+row.img" alt="">
          <!-- <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="路径" min-width="210px">
        <template slot-scope="{row}">
            <span>{{ row.link}}</span>
        </template>
      </el-table-column>
      <el-table-column label="小程序APPID" min-width="210px">
        <template slot-scope="{row}">
            <span>{{ row.isPages}}</span>
        </template>
      </el-table-column>



      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          {{ row.ishow | statusFilte }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='0'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">

        <el-form-item label="标题" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="跳转link" prop="link">
          <el-input v-model="temp.link" />
        </el-form-item>
        <el-form-item label="排序" >
          <el-input type="number" v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="小程序APPID" >
          <el-input v-model="temp.isPages" />
        </el-form-item>

        <el-form-item label="图片">
            <el-upload
              action=""
              accept="image/jpeg,image/png"
              :on-change="onUploadxqimg"
              :auto-upload="false"
              :show-file-list="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
              <div slot="tip" class="el-upload__tip">
                <p v-if="!temp.img">只能上传jpg/png文件，且不能超过1m</p>
                <p v-if="isupload">图片正在上传中...</p>
                <img v-if="imgurl" style="width:150px;" :src="imgurl" alt="">
                <img v-if="temp.img" style="width:150px;border:1px solid #f00;" :src="baseimgurl+temp.img" alt="">
                <el-button v-if="pic_files" size="small" @click="uploadimgsend" type="primary">点击上传</el-button>
              </div>

            </el-upload>
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-select v-model="temp.is_delete" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, idx) in statusOptions" :key="idx" :label="item.a" :value="item.b" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否展示">
          <el-switch
            v-model="temp.ishow"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </el-form-item>
        <!-- <el-form-item label="跳转小程序">
          <el-switch
            v-model="temp.isPages"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { fetchAiTools,  deleteStore, uploadAiIcon } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const __ = {
  formatDate: (date, fmt) => {
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  }
}

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    isfreeFn(status){

      if (status == 0) return '免费'
      if (status == 1) return '付费'
    },
    statusFilte(status) {
      // console.log(status, '======')
      if (status == 1) return '展示'
      if (status == 0) return '隐藏'
    },
    formatDate(time) {
      console.log(time)
      return __.formatDate(new Date(time * 1000), 'yyyy-MM-dd hh:mm:ss')
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      baseimgurl: 'https://zhouyitao.cc',
      pic_files: '',
      pic_files_list: {
        list: [],
        files: [],
      },
      catypeData: [
        { a: '全部', b: '' },
        { a: '免费', b: 0},
        { a: '付费', b: 1 }
      ],
      imgurl: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      isupload: false,
      listQuery: {
        page: 1,
        limit: 20,
        name:'',
        // importance: undefined,
        // ishow: '',
        // isfree: '',
        // sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ a: '全部', b: '' }, { a: '有效', b: 1 }, { a: '无效', b: 0}],
      showReviewer: false,
      temp: {
        name : '',
        link:'',
        img :'',
        ishow:true,
        sort: '',
        isPages: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑商品',
        create: '创建商品'
      },
      dialogPvVisible: false,
      rules: {  },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSwitchChange(value){
      console.log('Switch changed to:', value);
    },
    onUploadoicimg(file,fileList) {
      console.log(fileList)
      // return false;
      const _this = this
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false;
      }
      _this.pic_files_list.files=fileList;
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        // _this.temp.picimg = this.result;
        _this.pic_files_list.list.push(this.result);
          // console.log(this.result)//图片的base64数据
      }
    },
    onUploadxqimg(file) {
      const _this = this
      console.log(file)
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false;
      }
      this.pic_files = file;
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        // console.log(e.target)
        _this.imgurl = this.result;
          // console.log(this.result)//图片的base64数据
      }
    },
    uploadimgsend() {
      const  _this = this;
      var formFile = new FormData()
      formFile.append('brand_pic', this.pic_files.raw)
      this.isupload = true
      uploadAiIcon(formFile).then(response => {
        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.img = response.fileUrl
        _this.isupload = false
        _this.pic_files = null;
        _this.imgurl = '';
      })
      return false
    },
    getList() {
      this.listLoading = true
      fetchAiTools(this.listQuery,'/user/getbanner').then(response => {
        console.log(response)
        response.data.map(item => {
          item['ishow'] = !!item['ishow'];
          // item['isPages'] = !!item['isPages'];
            // item.img = item.img;
        })
        this.list = response.data
        this.total = response.count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        name : '',
        link:'',
        img :'',
        ishow:true,
        isPages: '',
        sort: '',
      }
      this.isupload = false
      this.pic_files = '';
      this.imgurl = '';
      this.pic_files_list = {
        list: [],
        files: [],
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // if (!this.temp.jifen && !this.temp.xianjin) return this.$message.error('请填写金额/积分')
      // if (!this.temp.img) return this.$message.error('请先上传图片')
      this.$refs['dataForm'].validate((valid) => {
        console.log(valid)
        if (valid) {
          // console.log(this.temp)
          const tempData = Object.assign({}, this.temp);
          tempData['ishow'] = Number(tempData['ishow']);
          // tempData['isPages'] = Number(tempData['isPages']);
          // tempData['isfree'] = 0;
          fetchAiTools(tempData,'/user/storebanner').then(() => {
            this.resetTemp()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp['list_pic_url'] = row['list_pic_url'].split(',');
      // this.temp.timestamp = new Date(this.temp.timestamp)
      // console.log(this.temp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.is_hot = +this.temp.is_hot;
          const tempData = Object.assign({}, this.temp);
          tempData['ishow'] = Number(tempData['ishow']);
          // tempData['isPages'] = Number(tempData['isPages']);
          // tempData['isfree'] = Number(tempData['isfree']);
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchAiTools(tempData,'/user/storebanner').then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.listLoading = true;
      this.$confirm(`确定要删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetchAiTools({id: row.id}, '/user/delbanner').then((res) => {
          console.log(res);
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });
      // this.list.splice(index, 1)
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
